const connection = require("../app/database");
const {to} = require("../utils");

class CommentService {
    async add(content, moment_id, userId) {
        const statement = `INSERT INTO comment (content,moment_id,user_id) values (?,?,?)`;
        const [error, resp] = await to(connection.execute(statement, [content, moment_id, userId]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }

    async reply(content, moment_id, comment_id, userId) {
        const statement = `INSERT INTO comment (content,moment_id,comment_id,user_id) values (?,?,?,?)`;
        const [error, resp] = await to(connection.execute(statement, [content, moment_id, comment_id, userId]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }

    // 查询某条动态的评论
    async list(moment_id, pageSize = 10, pageNo = 1) {
        // 查询页码总数
        const statement1 = `SELECT 
        COUNT(*) AS total
        FROM COMMENT c
        LEFT JOIN user u ON c.user_id = u.id
        WHERE moment_id = ?`;
        const [error1, resp1] = await to(connection.execute(statement1, [moment_id]));
        if (error1 || !resp1) {
            return Promise.reject(error1 || resp1);
        }
        const [values = []] = resp1;
        const {total} = values[0];

        // 分页接口
        const statement2 = `SELECT c.id id,c.content content,c.moment_id moment_id,c.createAt createTime,c.updateAt updateTime,
        JSON_OBJECT('id',u.id,'name',u.name) AS user
        FROM COMMENT c
        LEFT JOIN user u ON c.user_id = u.id
        WHERE moment_id = ?
        LIMIT ? OFFSET ?`;

        const [error2, resp2] = await to(
            connection.execute(statement2, [moment_id, pageSize + "", (pageNo - 1) * pageSize + ""])
        );

        if (error1 || error2) {
            return Promise.reject(error1 || error2);
        }
        const [list] = resp2;
        return {list, total};
    }

    async remove(id) {
        const statement = `DELETE FROM comment WHERE id = ?`;
        const [error, resp] = await to(connection.execute(statement, [id]));
        if (error) {
            return Promise.reject(error);
        }
        const [result] = resp;
        return result;
    }
}

module.exports = new CommentService();
